import { createApp } from 'vue'
import { registerMicroApps, start, setDefaultMountApp } from 'qiankun'
import App from './App.vue'
import router from './router'
import { initGlobalState, provideGlobalStateToVue } from './global-state'

// 初始化全局状态
const { onGlobalStateChange, setGlobalState } = initGlobalState({
  user: null,
  token: '',
  menu: [],
  breadcrumb: []
})
// 创建Vue应用
const app = createApp(App)
app.use(router)

// 提供全局状态管理给Vue应用
provideGlobalStateToVue(app)
app.mount('#app')

import { getMicroAppsConfig, getDefaultMicroAppName, getMicroAppsLifeCycles } from './micro-apps-config'

// 获取微应用配置
const microApps = getMicroAppsConfig({ onGlobalStateChange, setGlobalState })

// 获取生命周期钩子
const lifeCycles = getMicroAppsLifeCycles()
// 注册微应用
registerMicroApps(microApps, lifeCycles)

// 设置默认挂载的微应用
const defaultAppName = getDefaultMicroAppName()
const defaultApp = microApps.find(app => app.name === defaultAppName)
if (defaultApp) {
  setDefaultMountApp(typeof defaultApp.activeRule === 'string' ? defaultApp.activeRule : defaultApp.activeRule[0])
}

// 启动qiankun，配置沙箱
start({
  sandbox: {
    strictStyleIsolation: false,  // 禁用严格样式隔离以允许微应用样式正常加载
    experimentalStyleIsolation: true,  // 实验性样式隔离
    useSandbox: true
  },
  // 配置预加载策略 - 只预加载核心微应用
  prefetch: (apps) => {
    // 只预加载dashboard和auth两个核心微应用
    return apps.filter(app => app.name === 'micro-dashboard' || app.name === 'micro-auth')
  },
  // 配置错误处理
  errorHandler: (err: Error) => {
    console.error('[MicroFrontend] Error:', err)
    // 显示全局错误提示
    const errorEl = document.createElement('div')
    errorEl.className = 'micro-frontend-error global-error'
    errorEl.textContent = `微前端加载失败: ${err.message}`
    document.body.appendChild(errorEl)
    setTimeout(() => {
      document.body.removeChild(errorEl)
    }, 5000)
  },
  // 配置fetch策略，添加缓存支持
  fetch: (url, options) => {
    // 对静态资源添加缓存控制
    if (url.match(/\.(js|css|png|jpg|jpeg|svg|gif)$/)) {
      return window.fetch(url, {
        ...options,
        credentials: 'include',
        cache: 'force-cache'
      })
    }
    return window.fetch(url, options)
  },
  // 增加生命周期函数超时时间，解决single-spa #31错误
  timeout: 10000 // 设置为10秒超时
})

export { onGlobalStateChange, setGlobalState }